<?php
declare(strict_types=1);

namespace app\api\controller;

use app\api\service\BillUnPayedException;
use app\api\service\ChannelOrder as ChannelOrderService;
use app\api\service\CustomerRefreshException;
use app\api\service\SystemException;
use app\common\controller\Api;
use app\common\library\Pay;
use app\common\model\Area;
use app\common\model\delivery\ChannelGird;
use app\common\model\delivery\ChannelOrder;
use app\common\model\delivery\CouponList;
use app\common\model\delivery\Customer;
use app\common\model\delivery\CustomerAddress;
use app\common\model\delivery\Driver;
use app\common\model\delivery\MonthBill;
use app\common\model\delivery\PayLog;
use think\annotation\route\Get;
use think\annotation\route\Group;
use think\annotation\route\Post;

#[Group("buy")]
class Buy extends Api
{

   #[Post('createOrder')]
   public function createOrder()
   {
       $data=$this->request->post();
       $data['user_id']=$this->auth->id;
       $data['order_type']= ChannelOrder::ORDER_TYPE('用户下单');
       try {
           $payinfo=ChannelOrderService::newInstance($data)->createOrder();
       }catch (CustomerRefreshException $e) {
           $this->error($e->getMessage(),101);
       }catch (BillUnPayedException $e) {
           $this->error($e->getMessage(),102);
       }catch (SystemException $e) {
           $this->error($e->getMessage());
       }
       $this->success('',$payinfo);
   }

   #[Get('orderlist')]
   public function orderlist()
   {
       $param=$this->request->get();
       $offest=((int)$param['page']-1)*15;
       $list=ChannelOrder::with(['driver','goods','spec'])->where(function ($query) use ($param){
           $customer=Customer::find($param['customer_id']);
           $query->where('channel_id','=',$customer->channel_id);
           $query->where('customer_id','=',$customer->id);
           $query->where('is_cancel','=',0);
           $query->whereRaw("is_pay=1 or (pay_type='delivery' and is_pay=0)");
           if($param['order_type']==1){
               $query->whereNull('receive_time');
           }
           if($param['order_type']==2){
               $query->whereNotNull('receive_time');
           }
           if($param['order_type']==3){
               $query->where('refuse_number','>',0);
           }
       })->limit($offest,15)->order('id desc')->select();
       foreach ($list as $key=>$value){
           $list[$key]['pay_type']=ChannelOrder::PAY_TYPE[$value['pay_type']];
       }
       $this->success('',$list);
   }

   #[Post('cancel')]
   public function cancel()
   {
       $data=$this->request->post();
       /* @var ChannelOrder $order*/
       $order=ChannelOrder::where(['order_no'=>$data['order_no']])->find();
       $customerid=Customer::where("FIND_IN_SET({$this->auth->id},user_id)")->column('id');
       if(!$order || !in_array($order->customer_id,$customerid)){
           $this->error('订单不存在');
       }
       if($order->is_cancel==1){
           $this->error('订单已取消');
       }
       $order->cancelSuccess($order->number,'用户取消');
       $this->success('取消成功');
   }

    #[Get('contactDriver')]
    public function contactDriver($gird_id)
    {
        $gird=ChannelGird::find($gird_id);
        if($gird->drivers){
            $drivers=explode(',',$gird->drivers);
            $driver=Driver::where(['status'=>'normal','id'=>$drivers[0]])->find();
            if($driver){
                $this->success('',$driver);
            }
        }
        $this->error('该网格暂无司机配送，请联系客服');
    }

    #[Get('yuefu')]
    public function yuefu()
    {
        $customer_id=$this->request->get('customer_id');
        $goods_id=$this->request->get('goods_id');
        $customer=Customer::find($customer_id);
        $lastmonth=MonthBill::getLastMonthOrderDate($customer);
        $thismonth=MonthBill::getThisMonthOrderDate($customer);
        $last_month_yuefu=ChannelOrder::where(['customer_id'=>$customer_id,'goods_id'=>$goods_id,'is_cancel'=>0,'pay_type'=>'month'])->where('createtime','between',$lastmonth)->field('sum(total_money) as total_money,count(1) as count')->find();
        $month=date('Y-m',strtotime('-1 month'));
        $bill=MonthBill::where(['customer_id'=>$customer_id,'goods_id'=>$goods_id,'month'=>$month])->find();
        $last_month_yuefu['bill']=$bill;
        $this_month_yuefu=ChannelOrder::where(['customer_id'=>$customer_id,'goods_id'=>$goods_id,'is_cancel'=>0,'pay_type'=>'month'])->where('createtime','between',$thismonth)->field('sum(total_money) as total_money,count(1) as count')->find();
        $this->success('',[$last_month_yuefu,$this_month_yuefu]);
    }

    #[Get('yuefulist')]
    public function yuefulist()
    {
        $customer_id=$this->request->get('customer_id');
        $goods_id=$this->request->get('goods_id');
        $customer=Customer::find($customer_id);
        $month=$this->request->get('month');
        if($month==1){
            $lastmonth=MonthBill::getLastMonthOrderDate($customer);
            $list=ChannelOrder::with(['driver','goods','spec'])->where(['customer_id'=>$customer_id,'goods_id'=>$goods_id,'is_cancel'=>0,'pay_type'=>'month'])->where('createtime','between',$lastmonth)->select();
        }
        if($month==2){
            $thismonth=MonthBill::getThisMonthOrderDate($customer);
            $list=ChannelOrder::with(['goods','spec'])->where(['customer_id'=>$customer_id,'goods_id'=>$goods_id,'is_cancel'=>0,'pay_type'=>'month'])->where('createtime','between',$thismonth)->select();
        }
        foreach ($list as $key=>$value){
            $list[$key]['pay_type']=ChannelOrder::PAY_TYPE[$value['pay_type']];
        }
        $this->success('',$list);
    }

    #[Get('payYuefu')]
    public function payYuefu()
    {
        $bill_id=$this->request->get('bill_id');
        $platform=$this->request->get('platform');
        $bill=MonthBill::find($bill_id);
        $customer=Customer::withJoin(['channel'],'inner')->find($bill->customer_id);
        if(!$bill){
            $this->error('账单不存在');
        }
        if($bill->is_pay==1){
            $this->error('账单已支付');
        }
        $lastmonth=MonthBill::getLastMonthOrderDate($customer);
        $total_money=ChannelOrder::where(['customer_id'=>$bill->customer_id,'goods_id'=>$bill->goods_id,'is_cancel'=>0,'pay_type'=>'month','pay_id'=>null])->where('createtime','between',$lastmonth)->sum('total_money');
        if($total_money!=$bill->total_money){
            $this->error('账单金额不正确，请联系客服');
        }
        $orderNo=create_out_trade_no();
        $bill->order_no=$orderNo;
        $bill->save();
        $payinfo=(new Pay($customer->channel->sub_mch_id))->unifiedorder(
            $orderNo,
            $this->auth->id,
            floatval($bill->total_money),
            $bill->month.'月付账单',
            PayLog::TYPE('支付月付账单'),
            $platform
        );
        $this->success('',$payinfo);
    }

    #[Get('coupon')]
    public function coupon()
    {
        $customer_id=$this->request->get('customer_id');
        $goods_id=$this->request->get('goods_id');
        $where=[];
        $where[]=['coupon_list.customer_id','=',$customer_id];
        $where[]=['coupon_list.expire_time','>',time()];
        $where[]=['coupon.deletetime','=',null];
        $list=CouponList::where($where)->whereRaw('coupon_list.total>coupon_list.take')->withJoin(['coupon'],'right')->select();
        $r=[];
        foreach($list as $value){
            $desc='';
            if($value['coupon']['type']=='goods'){
                $desc='余额：'.($value['total']-$value['take']);
            }
            if($value['coupon']['type']=='card'){
                $desc='余额：￥'.$value['balance'];
            }
            if($value['coupon']['type']=='cash'){
                $desc='抵扣：￥'.$value['coupon']['cash'];
            }
            if($value['coupon']['type']=='discount'){
                $desc=$value['coupon']['discount'].'折';
            }
            if($value['coupon']['type']=='full_minus'){
                $full_minus=json_decode($value['coupon']['full_minus'],true);
                foreach ($full_minus as $man=>$jian){
                    $man=floatval($man);
                    $jian=floatval($jian);
                    $desc='满'.$man.'减'.$jian.'等优惠';
                    break;
                }
            }
            if(CouponList::checkGoods($value,$goods_id)){
                $r[]=[
                    'id'=>$value['id'],
                    'name'=>$value['coupon']['title'],
                    'desc'=>$desc,
                ];
            }
        }
        $this->success('',$r);
    }

    #[Get('address')]
    public function address()
    {
        $customer_id=$this->request->get('customer_id');
        $list=CustomerAddress::with(['area'])->where(['customer_id'=>$customer_id,'is_delete'=>0])->select();
        $this->success('',$list);
    }

    #[Post('setAddress')]
    public function setAddress()
    {
        $postdata=$this->request->post();
        $postdata['province_id']=$postdata['region'][0];
        $postdata['city_id']=$postdata['region'][1];
        $postdata['area_id']=$postdata['region'][2];
        $postdata['mergename']=Area::find($postdata['area_id'])->mergename;
        unset($postdata['region']);
        $postdata['info']=json_encode($postdata['info'],JSON_UNESCAPED_UNICODE);
        if($postdata['is_default']){
            CustomerAddress::where(['customer_id'=>$postdata['customer_id']])->update(['is_default'=>0]);
        }
        if($postdata['id']){
            CustomerAddress::update($postdata);
            $this->success('修改成功');
        }
        (new CustomerAddress())->save($postdata);
        $this->success('添加成功');
    }

    #[Post('delAddress')]
    public function delAddress()
    {
        $id=$this->request->post('address_id');
        $address=CustomerAddress::find($id);
        if($address->is_default){
            $this->error('默认地址不能删除');
        }
        $address->is_delete=1;
        $address->save();
        $this->success('删除成功');
    }
}